<template>
  <div class="discounts-wrap">
    <discounts-header></discounts-header>
    <div class="discounts-container">
      <div class="position-div" ref="positionDiv"></div>
      <discounts-block
        v-for="(item, index) in discountsList"
        :key="index"
        :list="item"
      ></discounts-block>
      <div class="load-more-wrap">
        <div v-if="!loading" >
          没有更多数据了，
          <span class="text" @click="refresh">刷新试试</span>
        </div>
        <div v-else class="huobo huobo-loading"></div>
      </div>
    </div>
  </div>
</template>

<script>
import DiscountsHeader from './components/Header.vue';
import DiscountsBlock from './components/Block.vue';

export default {
  name: 'DiscountsList',
  components: {
    DiscountsHeader,
    DiscountsBlock
  },
  data() {
    return {
      list: [],
      noData: false,
      loading: false,
      page: 1,
      per_page: 10
    };
  },
  computed: {
    discountsList() {
      const res = [];
      const len = this.list.length;
      for (let i = 0; i < len; i += 2) {
        res.push(this.list.slice(i, i + 2));
      }
      return res;
    }
  },
  created() {
    this.getData();
  },
  mounted() {
    const that = this;
    const intersectionObserver = new IntersectionObserver(entries => {
      const { isIntersecting } = entries[0];
      if (isIntersecting && !this.noData) {
        that.getData();
      }
    });
    intersectionObserver.observe(this.$refs.positionDiv);
  },
  methods: {
    refresh() {
      if (this.list.length % this.per_page) {
        this.page -= 1;
      }
      this.getData();
    },
    getData() {
      this.loading = true;
      this.$api.getCouponList({ page: this.page }).then(data => {
        this.loading = false;
        this.per_page = data.per_page;
        this.page += 1;
        data = data.data;
        const remain = this.list.length % this.per_page;
        if (remain) {
          data = data.slice(remain);
        }
        this.noData = !data.length;
        this.list.push(...data);
      }).catch(() => {
        this.loading = false;
      });
    }
  }
};
</script>

<style lang="less" scoped>
  @import '../../less/global.less';
  .discounts-container {
    position: relative;
  }
  .load-more-wrap {
    padding-bottom: 10px;
    line-height: 24px;
    text-align: center;
    background-color: #fff;
    .text {
      color: @mainBgColor;
      cursor: pointer;
    }
    .huobo-loading {
      margin: 0 auto;
      width: 20px;
      color: @mainBgColor;
      animation: loading 1s linear infinite;
      @keyframes loading {
        0% {
          transform: rotate(0);
        };
        50% {
          transform: rotate(180deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    }
  }
  .position-div {
    position: absolute;
    bottom: 400px;
    width: 100%;
  }
</style>
